//
//  ListInteractor.m
//  ViperDemo
//
//  Created by Leeesven on 17/5/19.
//  Copyright © 2017年 Leeesven. All rights reserved.
//

#import "ListInteractor.h"
#import "ListDataManager.h"
#import "Clock.h"
#import "NSCalendar+CalendarAdditions.h"
#import "TodoItem.h"
#import "NSArray+HOM.h"
#import "NearTermDateRelation.h"
#import "UpcomingItem.h"

@interface ListInteractor ()

@property (nonatomic, strong) ListDataManager *dataManager;
@property (nonatomic, strong) id<Clock>       clock;

@end

@implementation ListInteractor

-(instancetype)initWithDataManager:(ListDataManager *)dataManager clock:(id<Clock>)clock{
    if ((self = [super init]))
    {
        _dataManager = dataManager;
        _clock = clock;
    }

    return self;
}

-(void)findUpcomingItems{
    __weak typeof (self) welf = self;
    NSDate *today = [self.clock today];
    NSDate *endOfNextWeek = [[NSCalendar currentCalendar] dateForEndOfFollowingWeekWithDate:today];
    
    [self.dataManager todoItemsBetweenStartDate:today endDate:endOfNextWeek completionBlock:^(NSArray *todoItems) {
        [welf.output foundUpcomingItems:[welf upcomingItemsFromToDoItems:todoItems]];
    }];
}

- (NSArray *)upcomingItemsFromToDoItems:(NSArray *)todoItems{
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    
    NSArray *validTodoItems = (todoItems != nil) ? todoItems : @[];
    
    return [validTodoItems arrayFromObjectsCollectedWithBlock:^id(TodoItem *todoItem) {
        VTDNearTermDateRelation relation = [calendar nearTermRelationForDate:todoItem.dueDate relativeToToday:[self.clock today]];
        
        return [UpcomingItem upcomingItemWithDateRelation:relation dueDate:todoItem.dueDate title:todoItem.name];
    }];}

@end
